<template>
  <ex-dialog width="1000px" class="ex-diolog" :title="title" :visible="visible" @closeDialog="handleClose">
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="180px" class="demo-ruleForm" v-loading="loading">
      <div>
        <div class="lable_l">
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </div>
        <div class="bannerBox" v-for="(item, index) in ruleForm.bannerList" :key="200 + index">
          <div class="imgBox">
            <el-form-item label="轮播图名称:" :prop="`bannerList.${index}.name`" :rules="rules.name">
              <el-input type="text" v-model="item.name" autocomplete="off" placeholder="轮播图名称" :style="{ width: inputWidth }"></el-input>
            </el-form-item>
            <el-form-item label="图片:" :prop="`bannerList.${index}.imgUrl`" :rules="rules.imgUrl" ref="bannerUrlRef">
              <ImageUploadMore :limit="1" :fileSize="20" @successImg="(e) => { getBannerUrl(e, index) }"
                :value="item.imgUrl">
              </ImageUploadMore>
            </el-form-item>
            <el-form-item label="跳转方式:" :prop="`bannerList.${index}.skipType`" :rules="rules.skipType">
              <el-select v-model="item.skipType" placeholder="请选择" :style="{ width: inputWidth }">
                <el-option v-for="items in typeOptions" :key="items.id" :label="items.value" :value="items.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="填写跳转链接:" :prop="`bannerList.${index}.skipUrl`" :rules="rules.skipUrl" v-if="item.skipType=='2'" key="1">
              <el-input type="text" v-model="item.skipUrl" autocomplete="off" placeholder="请填写链接地址" :style="{ width: inputWidth }"></el-input>
            </el-form-item>
            <el-form-item label="选择插件:" :prop="`bannerList.${index}.pluginId`" :rules="rules.pluginId" v-if="item.skipType=='1'" key="2">
              <el-select v-model="item.pluginId" placeholder="请选择" :style="{ width: inputWidth }" @change="pluginChange($event,item,index)">
                  <el-option v-for="items in options" :key="items.id" :label="items.name" :value="items.id">
                  </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="选择跳转页面:" :prop="`bannerList.${index}.pageId`" :rules="rules.pageId" v-if="item.skipType=='1'" key="3">
              <el-select v-model="item.pageId" placeholder="请选择" :style="{ width: inputWidth }">
                  <el-option v-for="items in item.optionsView" :key="items.id" :label="items.name" :value="items.id">
                  </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="rig_btn_box">
            <el-button type="primary" circle icon="el-icon-arrow-up" @click="upGo(index)" v-if="index != 0"></el-button>
            <el-button type="primary" circle icon="el-icon-arrow-down" @click="downGo(index)"
              v-if="index != ruleForm.bannerList.length - 1"></el-button>
            <el-button type="danger" icon="el-icon-delete" circle @click="handleDelete(index)"></el-button>
          </div>
        </div>
      </div>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')" :loading="sumitLoading">确认</el-button>
        <el-button @click="handleClose('ruleForm')">取消</el-button>
      </el-form-item>
    </el-form>
  </ex-dialog>
</template>
<script>
// components
import Loading from '@/components/Loading/index'
// api
import {
  jtkHomePagebanner,jtkHomePagebannerSet,homePagePlugin,homePagePagePluginIdView
} from '@/api/incentiveManagement/adConfigNew'

export default {
  components: {
    Loading
  },
  props: {
    visible: Boolean,
    id: String,
    pathType: String,
  },
  data() {

    return {
      inputWidth: '400px',
      title: '轮播图配置',
      loading: false,
      sumitLoading: false,
      imgLoading: false,
      typeOptions:[
        {id:'1',value:'小程序插件'},
        {id:'2',value:'小程序链接'}
      ],
      options:[],
      optionsView:[],
      ruleForm: {
        bannerList:[
          {
            imgUrl: '',//图片地址
            name:'',//轮播图名称
            pageId:'',//页面ID
            pluginId:'',//插件ID
            skipType:'',//跳转方式小程序插件1 小程序链接2
            skipUrl:'',//跳转链接
            optionsView:[],//插件下拉
          }
        ],
      },
      rules: {
        name: [
          { required: true, message: '请输入轮播图名称', trigger: ['blur','change'] }
        ],
        imgUrl: [
          { required: true, message: '请上传图片', trigger: 'change' }
        ],
        skipType: [
          { required: true, message: '请选择跳转方式', trigger: ['blur','change'] }
        ],
        pageId: [
          { required: true, message: '选择跳转页面', trigger: ['blur','change'] }
        ],
        pluginId: [
          { required: true, message: '请选择插件', trigger: ['blur','change'] }
        ],
        skipUrl: [
          { required: true, message: '请输入跳转链接', trigger: ['blur','change'] }
        ],
      }
    }
  },
  computed: {

  },
  created() {
    this.getBanner()
    this.getHomePagePlugin()
  },
  methods: {
    //获取详情
    getBanner() {
      const params = {};
      this.loading = true
      jtkHomePagebanner(params).then((res) => {
        let bannerList = res.result
        bannerList.forEach(async (item,index)=>{
          item.optionsView = await this.getHomePagePagePluginId(item.pluginId)
        })
        this.ruleForm = {
          bannerList: bannerList
        }
        setTimeout(()=>{
          this.$forceUpdate()
          this.loading = false
        },1000)
      }).catch(()=>{
        this.loading = false
      })
      
    },
    //获取插件下拉列表
    getHomePagePlugin() {
      var data = {}
      homePagePlugin(data).then(res => {
        this.options = res.result
      })
    },
    //插件选择
    async pluginChange(e,item,index){
      this.ruleForm.bannerList[index].optionsView = await this.getHomePagePagePluginId(e)
      this.ruleForm.bannerList[index].pageId = ''
      // this.getHomePagePagePluginId(e)
      // this.ruleForm.bannerList[index].pageId = ''
    },
    //获取组件下拉
    getHomePagePagePluginId(pluginId){
      // homePagePagePluginIdView(pluginId).then(res => {
      //   this.optionsView = res.result
      // })
      let list = []
      return new Promise((resolve, reject) => {
        homePagePagePluginIdView(pluginId).then((res) => {
          list = res.result
          resolve(list)
        })
      });
    },
    //上传banner
    getBannerUrl(e, index) {
      this.ruleForm.bannerList[index].imgUrl = e
      this.$refs['bannerUrlRef'][index].clearValidate();
    },
    //新建
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.sumitLoading = true
          var data = this.ruleForm.bannerList
          jtkHomePagebannerSet(data).then(res => {
            setTimeout(() => {
              this.$message.success('操作成功')
              this.handleClose()
              this.$emit('success')
              this.sumitLoading = false
            }, 200);
          }).catch(() => {
            this.sumitLoading = false
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    //取消
    handleClose(formName) {
      this.$emit('update:visible', false)
      // this.$refs[formName].resetFields();
    },
    //新增轮播图
    handleAdd() {
      var obj = {
        imgUrl: '',//图片地址
        name:'',//轮播图名称
        pageId:'',//页面ID
        pluginId:'',//插件ID
        skipType:'',//跳转方式小程序插件1 小程序链接2
        skipUrl:'',//跳转链接
        optionsView:[],//插件下拉
      }
      this.ruleForm.bannerList.push(obj)
    },
    //删除轮播图
    handleDelete(ind) {
      this.ruleForm.bannerList.splice(ind, 1)
    },
    //上移一位
    upGo(index) {
      // console.log('index', index)
      var arr = this.ruleForm.bannerList
      if (index != 0) {
        // console.log(arr.splice(index - 1, 1, arr[index][0]))
        this.ruleForm.bannerList[index] = arr.splice(index - 1, 1, arr[index])[0]
        // console.log('arr', arr)
      } else {
        this.ruleForm.bannerList.push(arr.shift())
      }
    },
    //下移一位
    downGo(index) {
      var arr = this.ruleForm.bannerList
      if (index != arr.length - 1) {
        this.ruleForm.bannerList[index] = arr.splice(index + 1, 1, arr[index])[0]
      } else {
        this.ruleForm.bannerList.unshift(arr.splice(index, 1)[0])
      }
    }

  }
}
</script>
<style lang="scss" scoped>
.ex-diolog {
  ::v-deep .ex--dialog--footer {
    border: none !important;
    padding: 0 !important;
  }

  ::v-deep .ex--dialog--main {
    padding: 10px 20px !important;
  }
}

::v-deep .avatar-uploader2 .el-upload {
  width: 100% !important;
}

.avatar-uploader2 {
  width: 130px;
  height: 130px;
  text-align: center;
  line-height: 130px;
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
}

.banner_img {
  width: 130px;
  height: 130px;
}

.el-input {
  width: 300px;
}

.lable_l {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 20px 0 20px 80px;

  .left {
    margin-right: 20px;
  }
}

.bannerBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .rig_btn_box {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    width: 100px;
    height: 200px;

    .el-button {
      margin: 0;
    }
  }
}

.imgBox {
  border: 1px solid #f5f5f5;
  border-radius: 12px;
  padding: 20px;
  width: 800px;

  .name {
    font-size: 16px;
    color: #606266;
    margin-bottom: 10px;
    padding-left: 50px;
  }
}
</style>